﻿using Generico.Coneccion;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RosarioFinanzas.Sorteo
{
    public partial class PopTwuit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          this.Session.Add("Tipo",Convert.ToInt32(Request.QueryString["Tipo"]));
        }

        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            var cn = new ClsConeccion();
            cn.Abrir();
            cn.AgregarParametros("Mail", this.txtEmail.Text);
            cn.AgregarParametros("TipoIngreso", Convert.ToInt32(this.Session["Tipo"]));
            cn.AgregarParametros("IdSorteo", Convert.ToInt32(this.Session["IdSorteo"]));

            var rd = cn.EjecutarSpDataReader("sp_GrabarParticipante");
            while (rd.Read())
            {
                if (rd["nro"].ToString() == "-2" || rd["nro"].ToString() == "-3")
                {
                    Response.Write("<script> alert('Ya se encuentra participando');</script>");
                }
                else
                {
                    string str = this.Session["Sorteo"].ToString();
                    var correo = new System.Net.Mail.MailMessage
                    {
                        From = new System.Net.Mail.MailAddress("info@rosariofinanzas.com.ar")
                    };
                    correo.To.Add(this.txtEmail.Text);
                    correo.Subject = "SORTEO ROSARIO FINANZAS  -  " + this.Session["Sorteo"].ToString();
                    
                    string Body = GetHtmlEmailSorteo(this.Session["Sorteo"].ToString(), Convert.ToDateTime(this.Session["FechaSorteo"]).ToShortDateString(), rd["nro"].ToString());

                    List<string> list = new List<string>();

                    int c = 1;
                    while (Body.IndexOf("<img alt=\"\" src=\"http") > 0)
                    {
                        string aux = Body.Substring(Body.IndexOf("<img alt=\"\" src=\"http") + 17);
                        string aux2 = Body.Substring(Body.IndexOf("<img alt=\"\" src=\"http") + 17, aux.IndexOf("\" />"));
                        if (aux2.IndexOf("style") > 0)
                            aux2 = aux2.Substring(0, aux2.IndexOf("style") - 2);
                        list.Add(aux2);
                        Body = Body.Replace(aux2, "cid:Imagen" + c.ToString());
                        c++;
                    }

                    AlternateView htmlView =
                        AlternateView.CreateAlternateViewFromString(Body,
                                                Encoding.UTF8,
                                                MediaTypeNames.Text.Html);

                    c = 1;
                    foreach (string link in list)
                    {
                        LinkedResource img = null;
                        if (LinkExtension(link) == "Gif")
                            img = new LinkedResource(Link(link), MediaTypeNames.Image.Gif);
                        if (LinkExtension(link) == "jpg")
                            img = new LinkedResource(Link(link), MediaTypeNames.Image.Jpeg);
                        if (LinkExtension(link) != "jpg" && LinkExtension(link) != "Gif")
                            img = new LinkedResource(Link(link), "image/png");
                        img.ContentId = "Imagen" + c.ToString();
                        htmlView.LinkedResources.Add(img);
                        c++;
                    }

                    correo.AlternateViews.Add(htmlView);                    
                    
                    correo.Priority = System.Net.Mail.MailPriority.Normal;
                    var smtp = new System.Net.Mail.SmtpClient
                    {
                        Host = "mail.rosariofinanzas.com.ar",
                        Credentials =
                            new System.Net.NetworkCredential("info@rosariofinanzas.com.ar", "Info123456")
                    };
                    smtp.Send(correo);

                    if (Convert.ToInt32(this.Session["Tipo"]) == 2)
                    {
                        Response.Write("<script> alert('Su número de la suerte es  " + rd["nro"].ToString() + "'); window.open('http://www.facebook.com/sharer.php?u=http://rosariofinanzas.com.ar/Sorteo/Sorteo.aspx&t=" + str + "');window.parent.js_ClosePopUpJquery(); </script>");

                    }
                    else
                    {
                        Response.Write("<script> alert('Su número de la suerte es " + rd["nro"].ToString() + "'); window.open('http://twitter.com/share?url=http://rosariofinanzas.com.ar/Sorteo/Sorteo.aspx&text= " + str + "via @rosariofinanzas');window.parent.js_ClosePopUpJquery(); </script>");
                    }
                }
            }
            rd.Close();
            cn.Cerrar();
                      
        }

        private string LinkExtension(string Link)
        {
            return Link.Substring(Link.LastIndexOf(".") + 1);
        }

        private Stream Link(string link)
        {

            //This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            WebClient wc = new WebClient();
            byte[] b = wc.DownloadData(link);

            Stream ms = new MemoryStream(b);

            return ms;
        }

        private string GetHtmlEmailSorteo(string nombreSorteo, string fecha, string nro)
        {

            string html = "";

            // CABECERA
            html += "<div style=\"padding: 30px; height: auto; background-color: rgb(243, 238, 225);\">";
            html += "<div style=\"text-align: center;\">";
            html += "</div>";
            html += "<div style=\"text-align: center; background-color: white;\">";
            html += "<div style=\"width: 100%; height: 20px; background-color: rgb(141, 105, 13);\">";
            html += "</div>";
            html += "<table style=\"width: 96%; height: 120px; text-align: left; margin-top: 10px; margin-right: 2%; margin-left: 2%; border-bottom-color: rgb(141, 105, 13); border-bottom-width: 3px; border-bottom-style: double; background-color: white;\">";
            html += "<tbody>";
            html += "<tr>";
            html += "<td>";
            html += " <img alt=\"\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/RosarioNews.jpg\" style=\"width: 174px; height: 44px;\" /></td>";
            html += "<td style=\"text-align: right;\">";
            html += "<span style=\"font-family: arial,helvetica,sans-serif; font-size: 24px;\"><strong>Sorteos</strong></span><br />";
            html += "<br />";
            html += "<span style=\"color: black; font-family: arial,helvetica,sans-serif; font-size: 14px;\"><a href=\"http://rosariofinanzas.com.ar\" style=\"text-decoration: none;\">www.rosariofinanzas.com.ar</a></span></td>";
            html += "</tr>";
            html += "</tbody>";
            html += "</table>";


            // CUERPO
            html += "<p>";
            html += "Usted está participando en el sorteo '<strong>" + nombreSorteo + "'</strong> que se realizará el día <strong>" + fecha + "</strong>";
            html += "</p>";


            html += "<p>";
            html += "Su número es: <strong>" + nro + "</strong>";
            html += "</p>";


            // PIE
            html += "<p>";
            html += "Lea atentamente las <a href=\"http://rosariofinanzas.com.ar/Sorteo/BaseyCondiciones.aspx\" target=\"_blank\" style=\"text-decoration: none;\">Bases y Condiciones</a>";
            html += "</p>";
            html += "<div style=\"padding: 10px; height: 25px; text-align: right; background-color: rgb(141, 105, 13);\">";
            html += "<a href=\"https://www.facebook.com/pages/Rosario-Finanzas/197698343618378\" target=\"_blank\"><img alt=\"\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/face.png\" style=\"border-width: 0px; border-style: solid; width: 23px; height: 22px;\" /></a> <a href=\"https://twitter.com/rosariofinanzas\" target=\"_blank\"> <img alt=\"\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/twit.png\" style=\"border-width: 0px; border-style: solid; width: 23px; height: 22px;\" /></a></div>";
            html += "</div>";
            html += "</div>";
            html += "<p>";
            html += "</p>";

            return html;
        }

    }
}